﻿using Hangfire;
using Hangfire.Common;
using Hangfire.Server;
using Hangfire.States;
using Hangfire.Storage;

namespace Hangfire_Demo.HFCustom
{
    /// <summary>
    /// 自定义 作业状态过滤器
    /// EnqueuedState
    /// ScheduledState
    /// ProcessingState
    /// SucceededState
    /// FailedState
    /// DeletedState
    /// AwaitingState
    /// </summary>
    public class CustomApplyStateFilter : JobFilterAttribute, IApplyStateFilter, IServerFilter
    {
        public bool IsCancel;
        /// <summary>
        /// 执行前
        /// </summary>
        /// <param name="context"></param>
        public void OnPerforming(PerformingContext context)
        {

        }
        /// <summary>
        /// 执行完成后
        /// </summary>
        /// <param name="context"></param>
        public void OnPerformed(PerformedContext context)
        {
            if(context.Result != null) {
                if (context.Result.ToString().Contains("fault"))
                {
                    //context.Canceled = true;

                }
            }
        }



        /// <summary>
        ////  之后 在指定的状态应用于给定事务中的作业后调用。
        /// </summary>
        /// <param name="context"></param>
        /// <param name="transaction"></param>
        public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
        {
            if (context.NewState is SucceededState)
            {
                //context.NewState.
            }
        }

        //// 之前 当具有指定状态的状态未从中的作业应用时调用给定的事务。
        public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
        {
            if (context.NewState is SucceededState)
            {
                // 作业状态为成功时执行的操作
                // 可以在这里记录日志、发送通知等
                // 获取作业执行结果
                var result = (context.NewState as SucceededState).Result.ToString();

                if (result != null && !result.Contains("fail"))
                {
                    IsCancel = true;    
                    ////transaction.RemoveFromSet("succeeded", context.BackgroundJob.Id);
                    transaction.DecrementCounter("stats:succeeded");

                    //// 将作业状态更改为失败 
                    //// 事务插入记录到 State(JobId, Name, Reason, CreatedAt, Data)状态表，
                    //// 修改Job表记录 set StateId = SCOPE_IDENTITY(), StateName = @name where Id = @jobId;"
                    transaction.SetJobState(context.BackgroundJob.Id,
                        new FailedState(new System.Exception($"[自定义过滤器]\r\n任务结果\r\n{result}"))
                        );
                    //// 添加新的状态并覆盖现有状态
                    //// 插入记录到 State(JobId, Name, Reason, CreatedAt, Data)状态表，
                    //transaction.AddJobState(context.BackgroundJob.Id,
                    //    new FailedState(new System.Exception($"[自定义过滤器]--任务结果{result}"))
                    //    );
                }

                // 应用默认的状态更改逻辑

            }
        }
    }
}
